package middleware

import (
	"errors"
	"demo/models"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/sirupsen/logrus"
)

var mySigningKey = []byte("hourglass")
var ErrToken = errors.New("NOT FOUND TOKEN")

// 创建一个token
func CreateToken(user *models.Userinfo) (string, error) {
	claims := &models.MyCustomClaims{
		Userinfo: *user,
		RegisteredClaims: jwt.RegisteredClaims{
			//什么时候开始
			NotBefore: jwt.NewNumericDate(time.Now()),
			//设置24小时过期
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			//签发人
			Issuer: "lyz",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(mySigningKey)
}

// 解析token,返回用户信息
func ParseToken(tokenString string) (*models.Userinfo, error) {
	token, err := jwt.ParseWithClaims(tokenString, &models.MyCustomClaims{}, func(t *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		logrus.Errorln("解析token出错: ", err)
	}
	if token != nil {
		return &token.Claims.(*models.MyCustomClaims).Userinfo, nil
	} else {
		return nil, ErrToken
	}
}

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Cookie("jwt")
		token := c.Request.Header.Get("jwt")
		if token == "" {
			c.String(403, "权限受限，请先登录")
			c.Abort()
			return
		}
		userinfo, err := ParseToken(token)
		if err != nil {
			logrus.Errorln("解析Token签名失败:", err)
			c.Abort()
		}
		c.Set("user", userinfo)
		c.Next()
	}
}
